/**
 * Copyright (c) 2020, Mr.Wang (recallcode@aliyun.com) All rights reserved.
 */

package com.cpipec.demo.spi.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cpipec.demo.spi.EOSServerRestClient;
import com.spic.common.server.ServerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

/**
 * 调用技术中台基础服务接口实现
 */
@Component
public class EOSServerRestClientImpl implements EOSServerRestClient {

	private static Logger logger = LoggerFactory.getLogger(EOSServerRestClientImpl.class);

	@Value("${eos.system-id}")
	private String clientSysCode;

	@Value("${eos.server-http}")
	private String serverHttp;

	@Value("${eos.server-token}")
	private String serverToken;

	@Value("${security.iam.cookie.cookie-name-suffix}")
	private String cookieSuffixName;

	@Autowired
	private RestTemplate restTemplate;

	@Override
	public JSON getCurrentUser() {
		HttpHeaders requestHeaders = ServerUtils.createHeader(cookieSuffixName, serverToken);
		HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
		ResponseEntity<String> response = restTemplate.exchange(serverHttp + "/coframe/agent/ext/user/me", HttpMethod.GET, requestEntity, String.class);
		return (JSON) JSON.parse(response.getBody());
	}

	@Override
	public JSON getUserMenu() {
		HttpHeaders requestHeaders = ServerUtils.createHeader(cookieSuffixName, serverToken);
		HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
		JSON currentUser = this.getCurrentUser();
		if (ObjectUtils.isEmpty(currentUser)) throw new RuntimeException("未登录系统");
		ResponseEntity<String> response = restTemplate.exchange(serverHttp + "/coframe/agent/user-accounts/" + ((JSONObject) currentUser).get("id") + "/granted-menus", HttpMethod.GET, requestEntity, String.class);
		return (JSON) JSON.parse(response.getBody());
	}
}
